﻿using System;
using System.Data;
using Ice.Lib.Framework;
using Ice.Lib.Searches;

namespace Epicor.Pub
{
    /// <summary>添加UD表数据视图(EpiDataView)</summary>
    public class UDView
    {
        /// <summary>UD表名称</summary>
        public string udName;
        /// <summary>UD适配器</summary>
        public PubAdapter _udAdapter;
        /// <summary>UD表视图</summary>
        public EpiDataView _edvUD;
        /// <summary>oTrans</summary>
        public EpiTransaction oTrans;
        /// <summary>UD表DataTable</summary>
        public DataTable _udDataTable;
        /// <summary>UD表DataSet</summary>
        public DataSet _udDataSet;
        /// <summary>UD表视图的父视图</summary>
        public EpiDataView _Parent;
        /// <summary>UD表Key1</summary>
        public string _Key1;
        /// <summary>UD表Key2</summary>
        public string _Key2;
        /// <summary>UD表Key3</summary>
        public string _Key3;
        /// <summary>UD表Key4</summary>
        public string _Key4;
        /// <summary>UD表Key5</summary>
        public string _Key5;
        /// <summary>类初始化</summary>
        public UDView(EpiTransaction _oTrans, string _udName) {
            oTrans = _oTrans;
            udName = _udName;
        }
        /// <summary>初始化UD表适配器</summary>
        public void InitUDAdapter(string text,EpiDataView parent, string[] parentKeyFields, string[] childKeyFields)
        {
            _udAdapter = new PubAdapter(oTrans, udName);
            _udAdapter.BOConnect();
            _edvUD = new EpiDataView();
            _edvUD.dataView = new DataView(_udAdapter.GetCurrentDataSet().Tables[0]);
            _edvUD.AddEnabled = true;
            _edvUD.AddText = text;
            if ((oTrans.EpiDataViews.ContainsKey(udName+"View") == false))
            {
                oTrans.Add(udName + "View", this._edvUD);
            }
            _udDataSet = _udAdapter.GetCurrentDataSet();
            _udDataTable = _udDataSet.Tables[0];
            _edvUD.SetParentView(parent, parentKeyFields, childKeyFields);
        }
        /// <summary>获取UD表数据</summary>
        public void GetUDData(string key1, string key2, string key3, string key4, string key5)
        {
            string whereClause = GetWhereClause(new string[] { key1 , key2 , key3 , key4 , key5 });
            System.Collections.Hashtable whereClauses = new System.Collections.Hashtable(1);
            whereClauses.Add(udName, whereClause);
            SearchOptions searchOptions = SearchOptions.CreateRuntimeSearch(whereClauses, DataSetMode.RowsDataSet);
            _udAdapter.InvokeSearch(searchOptions);
            _edvUD.Row = (_udDataTable.Rows.Count > 0)? 0:-1;
            _edvUD.Notify(new EpiNotifyArgs(oTrans, _edvUD.Row, _edvUD.Column));
            _Key1 = key1;
            _Key2 = key2;
            _Key3 = key3;
            _Key4 = key4;
            _Key5 = key5;
        }

        private string GetWhereClause(string[] keys) {
            string whereClause = "";
            for (int i = 0; i < keys.Length; i++)
            {
                if (!string.IsNullOrEmpty(keys[i])) {
                    if (whereClause == "") whereClause += "Key" + (i + 1).ToString() + " = \'" + keys[i] + "\'";
                    else whereClause += " And Key" + (i + 1).ToString() + " = \'" + keys[i] + "\'";
                }
            }
            return whereClause;
        }
        /// <summary>保存修改的数据</summary>
        public void SaveUDRecord()
        {
            _udAdapter.Update();
        }
        /// <summary>删除当前选中的UD表数据</summary>
        public void DeleteUDRecord()
        {
            bool isAncestorView = false;
            EpiDataView parView = _edvUD.ParentView;
            while ((parView != null))
            {
                if ((oTrans.LastView == parView))
                {
                    isAncestorView = true;
                    break;
                }
                else
                {
                    parView = parView.ParentView;
                }
            }

            if (isAncestorView)
            {
                string whereClause = GetWhereClause(new string[] { _Key1, _Key2, _Key3, _Key4, _Key5 });
                DataRow[] drsDeleted = _udDataTable.Select(whereClause);
                for (int i = 0; (i < drsDeleted.Length); i = (i + 1))
                {
                    _udAdapter.Delete(drsDeleted[i]);
                }
            }
            else
            {
                if ((oTrans.LastView == _edvUD))
                {
                    if ((_edvUD.Row >= 0))
                    {
                        DataRow drDeleted = _udDataTable.Rows[_edvUD.Row];
                        if ((drDeleted != null))
                        {
                             _edvUD.Notify(new EpiNotifyArgs(oTrans, _edvUD.Row, _edvUD.Column));
                        }
                    }
                }
            }
        }
        /// <summary>取消UD表数据修改</summary>
        public void UndoUDChanges()
        {
            _udDataSet.RejectChanges();
            _edvUD.Notify(new EpiNotifyArgs(oTrans, _edvUD.Row, _edvUD.Column));
        }
        /// <summary>清空查询到的UD表数据</summary>
        public void ClearUDData()
        {
            _Key1 = string.Empty;
            _Key2 = string.Empty;
            _Key3 = string.Empty;
            _Key4 = string.Empty;
            _Key5 = string.Empty;
            _udDataSet.Clear();
            _edvUD.Notify(new EpiNotifyArgs(this.oTrans, this._edvUD.Row, this._edvUD.Column));
        }
        /// <summary>新增一行UD表数据</summary>
        public void GetNewUDRecord()
        {
            DataRow parentViewRow = _Parent.CurrentDataRow;
            if ((parentViewRow == null))return;
                
            if ((Boolean)_udAdapter.InvokeFun("GetaNew"+udName))
            {
                string ordernum = parentViewRow["OrderNum"].ToString();
                int rowCount = _udDataTable.Rows.Count;
                int lineNum = rowCount;
                bool goodIndex = false;
                while ((goodIndex == false))
                {
                    string whereClause = GetWhereClause(new string[] { _Key1, _Key2, _Key3, _Key4, lineNum.ToString() });
                    DataRow[] matchingRows = _udDataTable.Select(whereClause);
                    if ((matchingRows.Length > 0))lineNum = (lineNum + 1);
                    else goodIndex = true;
                }
                DataRow editRow = _udDataTable.Rows[(rowCount - 1)];
                editRow.BeginEdit();
                editRow["Key1"] = _Key1;
                editRow["Key2"] = _Key2;
                editRow["Key3"] = _Key3;
                editRow["Key4"] = _Key4;
                editRow["Key5"] = lineNum.ToString();
                editRow.EndEdit();
                _edvUD.Notify(new EpiNotifyArgs(oTrans, (rowCount - 1), _edvUD.Column));
            }
        }
        /// <summary>新增一行UD表数据</summary>
        public void baseToolbarsManager_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs args)
        {
            // EpiMessageBox.Show(args.Tool.Key);
            switch (args.Tool.Key)
            {
                case "ClearTool":
                    ClearUDData();
                    break;
                case "UndoTool":
                    UndoUDChanges();
                    break;
                case "SaveTool":
                    SaveUDRecord();
                    break;
                case "DeleteTool":
                    DeleteUDRecord();
                    break;
                case "RefreshTool":
                    GetUDData(_Key1, _Key2, _Key3, _Key4, _Key5);
                    break;
                default:
                    if (args.Tool.Key == _edvUD.AddText) {
                        GetNewUDRecord();
                    }
                    break;
            }
        }
    }

}
